package com.qipay.api.callback.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Map;

@RestController
@RequestMapping("/callback/v1/yitong")
/**
 * 亿通回调
 */
public class YitongCallbackController {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
	OrderService orderService;
    @Autowired
    SpConfigService spConfigService;

    @RequestMapping(value = "/wx" ,method = RequestMethod.POST)
    private String unionCreate(
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {
        Map<String, Object> responseMap = getRequestJson(request);
        logger.info("yitong-callback：params="+JSONObject.toJSONString(responseMap));
        if(responseMap==null||responseMap.get("status")==null||!"0".equals(responseMap.get("status").toString())){
            return "fail";
        }


        String orderNo = responseMap.get("order_no").toString();//对方订单号
        String userId = responseMap.get("user_id").toString();
        String shopNo = responseMap.get("shop_no").toString();//对方商家订单号（我方系统订单号）
        String money = responseMap.get("money").toString();
        String type = responseMap.get("type").toString();
        String tradeNo = responseMap.get("trade_no").toString();//交易流水号
        String fromSign = responseMap.get("sign").toString();

        Order order = orderService.getByTradeNo(shopNo);
        if(order==null) {
            logger.info("回调失败：查无此订单="+shopNo);
            return "fail";
        }
        Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
        String shopId = keyValues.get("shop_id").toString();
        String key = keyValues.get("key").toString();

        String signStr = shopId+userId+orderNo+key+money+type;
        String mySign = MD5Util.sign(signStr,"UTF-8").toLowerCase();
        if(fromSign.equals(mySign)){
            order.setSpTradeNo(orderNo);
            orderService.update(order);
            orderService.setOrderSuccess(order.getId(), null);
        }else {
            logger.info("回调失败：签名sign不一致");
        }
        return "success";
    }

    public static JSONObject getRequestJson(HttpServletRequest request){
        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder resContent = new StringBuilder();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                resContent.append(java.net.URLDecoder.decode(temp, "UTF-8"));
            }
            br.close();

            String line = resContent.toString();
            if(line.startsWith("\uFEFF")){
                line = line.replace("\uFEFF", "");
            }
            JSONObject notifyJson = new JSONObject();
            try {
                notifyJson = JSONObject.parseObject(line);
            } catch (Exception e) {
                String param[] = line.split("&");
                for (String content : param) {
                    if (content.indexOf("=") > 0) {
                        String key = content.substring(0, content.indexOf("="));
                        String value = content.substring(content.indexOf("=") + 1, content.length());
                        notifyJson.put(StringUtils.deleteWhitespace(key), StringUtils.deleteWhitespace(value).replace("\"", ""));
                    }else if (content.indexOf(":") > 0) {
                        String key = content.substring(0, content.indexOf(":"));
                        String value = content.substring(content.indexOf(":") + 1, content.length());
                        notifyJson.put(StringUtils.deleteWhitespace(key), StringUtils.deleteWhitespace(value).replace("\"", ""));
                    }
                }
            }
            return notifyJson;
        } catch (Exception e) {
            return null;
        }

    }

}
